import {
  request
} from '../../utils/request.js'
let app = getApp();
// import _ from 'lodash'
Page({

	/**
	 * 页面的初始数据
	 */
  data: {
    cart: [],
    newCart: [],
    cartNumber: 0,
    selectAllStatus: false,
    totalMoney: 0,
    pre: '运费说明：满200元免邮费（不含自提价）',
    address: {},
    flag: '',
    song: 0,
    sMoney: 0,
    delPrice: 0,
    delivery: '物流配送',
    clickTrue: true,
    sumMoney: '',
    ps_type:1,
    show:false,
    radio:0,
    peisTime:[],
    peisTime_selected:'',
    fare:0,
    showAll:false,
    cartLength:0
  },
  onShow() {
    this.addressList()
    
    this.activity()
    
  },

	/**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function (options) {
    let objArr = [{ id: 1, name: 2 }, { id: 1, name: 1 }]
    let res3 = this.uniqObjInArray(objArr);

    this.getInitGoods()
    
    this.setData({
      cartLength:this.data.cart.length,
      cart: [this.data.cart[0]],
    })
    
    
    console.log(this.data.cart[0])

    let type = 1
    if (wx.getStorageSync('selectType')) {
      type = wx.getStorageSync('selectType')
    }
    // 获取配送时间段
    request({
      url: `getDelivery?type=${type}`,
      token: wx.getStorageSync('token'),
      method: 'POST',
    }).then(res=>{
      console.log(res)
      const data = res.data.data.list
      this.setData({
        peisTime:data
      })
      console.log(this.data.peisTime)
    })

    
    // 运费
    this.fare()
    // 起送规则
    this.sendRule()

  },

  // 初始化获取订单列表
  getInitGoods(){
    let totalMoney = 0
    let param = this.getUrlkey(this.getCurrentPageUrlWithArgs())
    let newCart = []


    this.setData({
      cart: JSON.parse(param.orderInfo)
    })
    console.log('orderInfo-----------', param)
    this.data.cart.forEach(item => {
      item.totalOne = (item.market_price * item.number).toFixed(2)

      newCart.push({ product_id: item.id, count: item.number })
      if (item.number != 0) {
        totalMoney = totalMoney + item.market_price * item.number
      }

    })

    this.setData({
      totalMoney: totalMoney.toFixed(2),
      newCart,
      cart: this.data.cart,
      sumMoney: totalMoney.toFixed(2)
    })
  },

  // 运费
  fare(){
    request({
      url: `deliverRule?total_money=${this.data.totalMoney}`,
      token: wx.getStorageSync('token'),
      method: 'POST',
    }).then(res => {
      console.log(res)
      var money = parseFloat(res.data.data) + parseFloat(this.data.totalMoney)
      this.setData({
        fare:res.data.data,
        totalMoney: money
      })
      wx.setStorageSync('fare', res.data.data)
    })
  },

  // 列表的展开和折叠
  toggleGoods(){
    this.getInitGoods();
    this.activity()
    this.setData({
      showAll: !this.data.showAll
    })
    if (!this.data.showAll){
      this.setData({
        cart: [this.data.cart[0]],
      })
    }

    let money = parseFloat(this.data.fare) + parseFloat(this.data.totalMoney)
    this.setData({
      totalMoney: money
    })



  },

  uniqObjInArray(objarray) {
    let len = objarray.length;
    let tempJson = {};
    let res = [];
    for (let i = 0; i < len; i++) {
      //取出每一个对象
      tempJson[JSON.stringify(objarray[i])] = true;
    }
    // console.log("tempJson is ", tempJson);
    let keyItems = Object.keys(tempJson);
    for (let j = 0; j < keyItems.length; j++) {
      res.push(JSON.parse(keyItems[j]));
    }
    return res;
  },

  /** 
   * 取消订单
  */
  delOrder() {
    wx.switchTab({ url: `/pages/shopCart/shopCart` });
  },

  /** 
   * 获取当前页面的url参数
  */
  getCurrentPageUrlWithArgs() {
    let pages = getCurrentPages() //获取加载的页面
    let currentPage = pages[pages.length - 1] //获取当前页面的对象
    let url = currentPage.route //获取当前页面的url
    let options = currentPage.options //如果要获取url中所带的参数,可查看options
    //拼接url的参数
    let urlWithArgs = url + '?'
    for (let key in options) {
      let value = options[key]
      urlWithArgs += key + '=' + value + '&'
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
    return urlWithArgs
  },

  /**
   * 获取url中的参数
   */
  getUrlkey(url) {
    urls = this.getCurrentPageUrlWithArgs()
    let params = {}
    let urls = url.split('?')
    if (urls[1]) {
      let arr = urls[1].split('&')
      for (let i = 0, l = arr.length; i < l; i++) {
        let a = arr[i].split('=')
        params[a[0]] = a[1]
      }
      return params
    } else {
      return urls[0]
    }
  },

  // 配送时间
  peis_btn:function(){
    this.setData({
      show:true
    })
  },
  changeTime:function(event){
    this.setData({
      radio: event.detail,
      peisTime_selected:event.detail
    });
    var that = this
    setTimeout(function(){
      that.setData({
        show: false
      });
    },500)

  },


  /** 
   * 创建订单
  */
  createConsultation() {
    if(this.data.peisTime_selected==''){
      wx.showToast({
        title: '请选择配送时间', //提示的内容,
        icon: 'none',
        duration: 2000, //延迟时间,
        mask: true, //显示透明蒙层，防止触摸穿透,
      })
      return false
    }

    if (this.data.clickTrue) {
      wx.showLoading({
        title: '正在下单中...', //提示的内容,
        mask: true, //显示透明蒙层，防止触摸穿透,
      });
      this.setData({
        clickTrue: false
      })

      let that = this
      let products = that.data.newCart
      request({
        url: `order`,
        token: wx.getStorageSync('token'),
        method: 'POST',
        data: {
          products,
          delivery: that.data.delivery,
          deliveryTime: that.data.peisTime_selected,
          fees:that.data.fare
        }
      }).then(res => {
        // console.log('创建订单结果', res)
        if (res.data.pass == true) {

          // console.log('成功', res.data.order_id, wx.getStorageSync('token'))
          wx.setStorageSync('order_id', res.data.order_id);
          that.getPreOrder(wx.getStorageSync('token'), res.data.order_id);
          // console.log('创建订单结果111', res.data)
          that.data.newCart.forEach(item => {
            request({
              url: `setNum`,
              token: wx.getStorageSync('token'),
              method: 'POST',
              data: {
                productId: item.product_id,
                number: 0
              }
            }).then(res => {
            })
          })
        } else {
          console.log('失败', res.data.order_id)
        }
      })
    }

  },
 
  getPreOrder(token, orderID) {
    if (token) {
      request({
        url: `/pay/pre_order`,
        token: token,
        method: 'POST',
        data: {
          id: orderID
        }
      }).then(res => {
        console.log('创建订单结果', res)
        var preData = res.data;
        console.log('支付结果', res.data)
        wx.requestPayment({
          timeStamp: preData.timeStamp.toString(),
          nonceStr: preData.nonceStr,
          package: preData.package,
          signType: preData.signType,
          paySign: preData.paySign,
          success: function (res) {
            wx.hideLoading();
            console.log(res.data);
            wx.navigateTo({ url: '/pages/payTwo/payTwo' });
          },
          fail: function (error) {
            wx.hideLoading();
            console.log(error);
            wx.showModal({
              title: '提示',
              content: '订单未支付（30分钟内订单不支付，订单将自动取消，请尽快支付）',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({ url: '/pages/payOne/payOne' });
                } else if (res.cancel) {

                }
              }
            })
          }
        })
      })

    }
  },


  /** 
   * 获取用户地址
  */
  addressList() {
    request({
      url: `addressList`,
      token: wx.getStorageSync('token'),
      method: 'POST',
      data: {
        type: 1,
      }
    }).then(res => {
      console.log('默认地址', res.data.data[0])
      this.setData({
        address: res.data.data[0]
      })
    })
  },
  /** 
   * 选择地址
  */
  selectAddress() {
    wx.navigateTo({ url: `/pages/addressList/index` });
  },

  bySelf() {
    wx.showToast({
      title: '选择了到店自取', //提示的内容,
      icon: 'none', //图标,
      duration: 1500, //延迟时间,
      mask: true, //显示透明蒙层，防止触摸穿透,
      success: res => { }
    });
    if (this.data.ps_type!=2){
      let totalMoney = this.data.totalMoney - 1 + 1 - this.data.fare
      this.setData({
        totalMoney: totalMoney.toFixed(2)
      })
    }
    
    this.setData({
      flag: true,
      delivery: '到店自取',
      ps_type:2,
      fare:0,
      
    })

  },
  wuliu() {
    wx.showToast({
      title: '选择了物流配送', //提示的内容,
      icon: 'none', //图标,
      duration: 1500, //延迟时间,
      mask: true, //显示透明蒙层，防止触摸穿透,
      success: res => { }
    });
    
    const fees = wx.getStorageSync("fare");
    console.log(fees)
    if (this.data.ps_type != 1) {
      let totalMoney2 = parseFloat(this.data.totalMoney) + parseFloat(fees)
      this.setData({
        totalMoney: totalMoney2.toFixed(2)
      })
    }
    this.setData({
      delivery: '物流配送',
      ps_type: 1,
      fare:fees
    })
    
    if (parseInt(this.data.totalMoney) < this.data.song) {
      this.setData({
        flag: false,
      })
    } else {
      this.setData({
        flag: true,
      })

    }


  },
  /** 
 * 邮费说明
*/
  sendRule() {
    request({
      url: `sendRule`,
      token: wx.getStorageSync('token'),
      method: 'POST',
    }).then(res => {
      console.log('total', this.data.totalMoney)
      console.log('接口返回价格', res.data.money)

      if (parseFloat(this.data.totalMoney) > res.data.money) {

        this.setData({
          flag: true,
        })
        console.log('邮费请求结果', this.data.flag)

      } else {
        this.setData({
          flag: false

        })
      }
      this.setData({
        song: res.data.money,
        sMoney: (res.data.money - this.data.totalMoney).toFixed(2)
      })


    })

  },
  // 满减
  activity() {
    console.log(111111)
    let that = this
    let money = 0
    money = parseFloat(this.data.totalMoney)
    console.log(22222222, app.globalData.url)
    wx.request({
      url: app.globalData.url + 'activity',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        token: wx.getStorageSync('token')
      },
      method: 'POST',
      data: {
        money
      },
      success: res => {
        console.log(333333333)
        that.setData({
          totalMoney: (parseFloat(that.data.totalMoney) - parseFloat(res.data.reduction)).toFixed(2),
          delPrice: Math.abs(res.data.reduction)
        })

      }

    })
  }

})
